package com.bvgol.examples.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @program: my-spring-completely
 * @description: Scattering(散射) 往buffer 数组写的是,第一个满了再第二个
 *               Gathering(搜集) 从buffer 数组读,依次读
 * @author: GUOCHEN
 * @create: 2021/06/18 15:09
 */
public class TestScatteringAndGathering {
    public static void main(String[] args) throws IOException {

        //使用 channel 网络
        ServerSocketChannel open = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口并启动
        open.socket().bind(inetSocketAddress);

        //创建buffer 数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接 telnet
        SocketChannel accept = open.accept();

        //假定从客户端接收8个字符
        int messageLength = 8;
        while (true){
            int bytesRead=0;
            //读/in
            while (bytesRead<messageLength){
                long read = accept.read(byteBuffers);
                System.out.println("bytesRead+=read = " + (bytesRead += read));
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "postion= "+byteBuffer.position()+" ,limit= "+byteBuffer.limit()).forEach(System.out::println);
            }
            //反转
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

            //写/out
            long byteWirte = 0;
            while (byteWirte<messageLength){
                long write = accept.write(byteBuffers);
                System.out.println("(byteWirte+=write) = " + (byteWirte += write));
            }

            //重置
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());

        }

    }
}
